/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import request from '@base/utils/request';
import { message } from 'antd';
import { isArray, isFunction } from 'lodash';

interface TableRequestParams {
  current?: number;
  pageSize?: number;
}

/**
 *
 * @description 报错操作错误消息
 * @param res
 * @returns
 */
export function operateError(res: any) {
  const { code, msg } = res || {};
  if (code > 0 && msg) {
    message.error(msg);
  }
  return res;
}

/**
 *
 * @description 操作成功提示
 * @param res
 * @returns
 */
export function operateSuccess(res: any) {
  const { code, msg } = res || {};
  if (code == 0 && msg) {
    message.success(msg);
  }
  return res;
}

/**
 *
 * @description 格式化操作结果
 * @param res
 * @returns
 */
export function operateFormat(res: any) {
  const { code, msg } = res || {};
  if (code == 0) {
    return {
      code,
      data: true,
    };
  }
  return {
    code,
    msg,
  };
}

export async function formatTableRequest<T>(
  url: string,
  params: TableRequestParams & T,
  filterReq?: (p: T) => T | Promise<T>,
) {
  const { current: page, pageSize: page_size, ...rest } = params;
  let req = {
    page,
    page_size,
    ...rest,
  } as T;
  if (isFunction(filterReq)) {
    req = (await filterReq(req)) || req;
  }
  return request(url, {
    method: 'POST',
    data: req,
  }).then((res) => {
    const { data, list = data as any[], total, ...restData } = res.data || {};
    return {
      data: isArray(list) && list.length > 0 ? list : null,
      success: true,
      total,
      ...restData,
    };
  });
}
